package com.kevin.controller.controller;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.FIFOCache;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kevin.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 抖音工具类
 * <p>
 * 参考 https://xiang007.com/2023/04/07/%E6%8A%96%E9%9F%B3%E8%A7%86%E9%A2%91%E5%8E%BB%E6%B0%B4%E5%8D%B0%E6%8E%A5%E5%8F%A3%E5%88%86%E6%9E%90%E9%99%84%E4%BB%A3%E7%A0%81/
 *
 * @author wh
 * @date 2023-12-26 15:11
 */
@Slf4j
public class DyUtil {
    static FIFOCache<Object, Object> cache = CacheUtil.newFIFOCache(1, 60 * 60 * 3);


    static String odin_tt = "324fb4ea4a89c0c05827e18a1ed9cf9bf8a17f7705fcc793fec935b637867e2a5a9b8168c885554d029919117a18ba69; ttwid=1%7CWBuxH_bhbuTENNtACXoesI5QHV2Dt9-vkMGVHSRRbgY%7C1677118712%7C1d87ba1ea2cdf05d80204aea2e1036451dae638e7765b8a4d59d87fa05dd39ff";
    static String ttwid = "ttwid=1%7C7ZLJzwjjEw7NLeADTpVd-3eId-ZEIg0jpCEzTV9p_2A%7C1677681848%7C4ff4f97328ddc18b6d46c259bc26a05d2e654b50e3f21b27b8f9e9e8f9fcec82; Path=/; Domain=bytedance.com; Max-Age=31536000; HttpOnly; Secure;";
    static String ticket = "bd_ticket_guard_client_data=eyJiZC10aWNrZXQtZ3VhcmQtdmVyc2lvbiI6MiwiYmQtdGlja2V0LWd1YXJkLWNsaWVudC1jc3IiOiItLS0tLUJFR0lOIENFUlRJRklDQVRFIFJFUVVFU1QtLS0tLVxyXG5NSUlCRFRDQnRRSUJBREFuTVFzd0NRWURWUVFHRXdKRFRqRVlNQllHQTFVRUF3d1BZbVJmZEdsamEyVjBYMmQxXHJcbllYSmtNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUVKUDZzbjNLRlFBNUROSEcyK2F4bXAwNG5cclxud1hBSTZDU1IyZW1sVUE5QTZ4aGQzbVlPUlI4NVRLZ2tXd1FJSmp3Nyszdnc0Z2NNRG5iOTRoS3MvSjFJc3FBc1xyXG5NQ29HQ1NxR1NJYjNEUUVKRGpFZE1Cc3dHUVlEVlIwUkJCSXdFSUlPZDNkM0xtUnZkWGxwYmk1amIyMHdDZ1lJXHJcbktvWkl6ajBFQXdJRFJ3QXdSQUlnVmJkWTI0c0RYS0c0S2h3WlBmOHpxVDRBU0ROamNUb2FFRi9MQnd2QS8xSUNcclxuSURiVmZCUk1PQVB5cWJkcytld1QwSDZqdDg1czZZTVNVZEo5Z2dmOWlmeTBcclxuLS0tLS1FTkQgQ0VSVElGSUNBVEUgUkVRVUVTVC0tLS0tXHJcbiJ9";

    private static List<String> UA_LIST = new ArrayList<String>() {{
        add("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36");
        add("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0");
    }};

    public static String getVideoId(String url) {
        url = ReUtil.get("\\S*?(https://v\\.douyin\\.com/[^/\\s]+)\\S*?", url, 0);
        if (StrUtil.isEmpty(url)) {
            throw new BusinessException("解析url失败");
        }
        HttpResponse execute = HttpUtil.createGet(url).execute();
        String location = execute.header("Location");
        return ReUtil.get("(\\d+)", location, 1);
    }

    public static JSONObject analyze(String url) {
        String videoId = getVideoId(url);
        String part1 = "&device_platform=webapp&channel=channel_pc_web&aid=6383&os_version=10";
        String part2 = "&aid=1128&version_name=23.5.0&device_platform=android&os_version=2333";
        String realUrl = String.format("https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids=%s" + part1, videoId);
        String ua = UA_LIST.get(RandomUtil.randomInt(UA_LIST.size()));

        String finalRealUrl = realUrl;
        realUrl = JSON.parseObject(HttpUtil.post("http://localhost:8787/X-Bogus", JSON.toJSONString(new HashMap<String, Object>() {{
            put("url", finalRealUrl);
            put("user_agent", ua);
        }}))).getString("param");

        HttpRequest request = HttpUtil.createGet(realUrl);
        request.cookie(String.format("msToken=%s;odin_tt=%s;ttwid=%s;bd_ticket_guard_client_data=%s", getMsToken(), odin_tt, ttwid, ticket));
        request.header("User-Agent", ua);
        request.header("Referer", "https://www.douyin.com/");
        request.header("Origin", "https://www.douyin.com");

        return JSON.parseObject(request.execute().body());
    }

    public static String getMsToken() {
        return RandomUtil.randomString("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 107);
//        Object msToken = cache.get("msToken");
//        if (msToken == null) {
//            msToken = RandomUtil.randomString("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 107);
//            cache.put("msToken", msToken);
//        }
//        return (String) msToken;
    }
}
